package org.lewis.demo.util;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class WebClientUtil {

    @Value("${url.gitee.user-info}")
    private String userInfoUrl;
    @Value("${url.gitee.public-events}")
    private String publicEventsUrl;
    @Value("${url.gitee.public-repos}")
    private String publicReposUrl;

    private final WebClient webClient = WebClient.create();

    public JsonNode userInfo(String username) {
        Mono<JsonNode> mono = this.webClient.get().uri(this.userInfoUrl, username)
                .retrieve().bodyToMono(JsonNode.class);
        return mono.block();
    }

    public byte[] avatar(String username) {
        Mono<JsonNode> mono1 = this.webClient.get().uri(this.userInfoUrl, username)
                .retrieve().bodyToMono(JsonNode.class);
        String avatarUrl = mono1.block().path("avatar_url").asText();

        Mono<byte[]> mono2 = this.webClient.get().uri(avatarUrl)
                .retrieve().bodyToMono(byte[].class);
        return mono2.block();
    }

    public JsonNode publicEvents(String username) {
        Mono<JsonNode> mono = this.webClient.get().uri(this.publicEventsUrl, username)
                .retrieve().bodyToMono(JsonNode.class);
        return mono.block();
    }

    public List<JsonNode> publicRepos(String username) {
        Flux<JsonNode> flux = this.webClient.get().uri(this.publicReposUrl, username)
                .retrieve().bodyToFlux(JsonNode.class);
        return flux.collectList().block();
    }

}
